package com.example.bookmanagement.config;

import com.example.bookmanagement.exception.JwtAuthenticationEntryPoint;
import com.example.bookmanagement.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationEntryPoint authEntryPoint;

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // CSRF禁用，因为不使用session
                .csrf().disable()
                 // 禁用 X-Frame-Options 头
                .headers().frameOptions().disable()
                // 无状态会话管理
                .and().sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 异常处理（自定义 401/403 响应）
                .exceptionHandling(exceptions -> exceptions
                        .authenticationEntryPoint(authEntryPoint)  // 未认证处理
                        .accessDeniedHandler(authEntryPoint)       // 权限不足处理
                        )
               .authorizeRequests()
               .antMatchers("/api/auth/login", "/swagger-ui/**", "/v3/api-docs/**","/swagger-resources/**").permitAll()
                .anyRequest().authenticated()// 其他所有请求需要认证
                .and().cors().configurationSource(corsConfigurationSource())
                .and()
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();

    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));// 允许跨域访问
        configuration.setAllowedMethods(Arrays.asList("*")); // 允许的方法
        configuration.setAllowedHeaders(Arrays.asList("*")); // 允许的请求头
        //configuration.setAllowCredentials(true); // 允许携带凭证（如Cookie）

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration); // 对所有路径生效
        return source;
    }
}    